package com.laicunba.ext.activity.act20170726;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.laicunba.pojo.ActivityDO;
import com.laicunba.pojo.CashCouponDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.CashCouponService;
import com.laicunba.service.activity.ActivityChanceService;
import com.laicunba.util.AssertUtil;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;

@Service
public class Act20170627ChanceService implements ActivityChanceService {
	@Autowired
	private CashCouponService cashCouponService;

	@Override
	public String getActivityId() {
		return "20170726gqkg";
	}

	@Override
	public boolean hasChance(UserDO userDO, ActivityDO activityDO, String subActId) {

		String couponCacheKey = "act.20170726gqkg.coupon." + DateUtil.formatDate(new Date());
		Map<String, String> couponMap = CacheUtil.hgetAll(couponCacheKey);
		if (couponMap == null || couponMap.isEmpty()) {
			AssertUtil.assertFail("STORE_EMPTY");
		}

		List<CashCouponDO> couponList = cashCouponService.findUseableCashCoupon(userDO.getId());
		int couponHoldAmt = 0;
		if (couponList != null) {
			for (CashCouponDO coupon : couponList) {
				if (subActId.equalsIgnoreCase(coupon.getDefId())) {
					couponHoldAmt++;
				}
			}
		}
		if (couponHoldAmt >= 2) {
			AssertUtil.assertFail("MORE_2");
		}
		boolean isPm = new Date().getHours() >= 15;
		if (!isPm) {
			// 早上场
			String amStore = couponMap.get("am." + subActId);
			if (Integer.parseInt(amStore) <= 0) {
				AssertUtil.assertFail("AM_STORE_EMPTY");
			}
			CacheUtil.hset(couponCacheKey, "am." + subActId, Integer.toString(Integer.parseInt(amStore) - 1));
			return true;
		} else {
			// 下WU场
			String amStore = couponMap.get("am." + subActId);
			if (Integer.parseInt(amStore) >= 1) {
				CacheUtil.hset(couponCacheKey, "am." + subActId, Integer.toString(Integer.parseInt(amStore) - 1));
				return true;
			}

			amStore = couponMap.get("pm." + subActId);
			if (Integer.parseInt(amStore) >= 1) {
				CacheUtil.hset(couponCacheKey, "pm." + subActId, Integer.toString(Integer.parseInt(amStore) - 1));
				return true;
			}
			AssertUtil.assertFail("PM_STORE_EMPTY");
		}
		return false;
	}

}
